<template>
  <div class="c-bg-sgray">
    <div class="c-p">
      <swiper v-if="swiperList.length > 0" id="mySwiper" ref="mySwiper" :options="swiperOption" class="c-bg-white c-p">
        <swiper-slide v-for="(item, index) in swiperList" :key="index" class="c-p">
          <div>
            <img :class="'swiper-img' + index" class="c-w100" :src="$addXossFilter(item)">
          </div>
        </swiper-slide>
        <div class="swiper-pagination" slot="pagination">
          <div class="c-pa c-p-r0 c-p-b0 c-pr24 c-ww100 c-pb28 c-flex-row c-justify-end">
            <div class="swiper-page-tag c-fs20 c-flex-row c-flex-center">
              {{swiperIndex + 1}}/{{swiperList.length}}
            </div>
          </div>
        </div>
      </swiper>
    </div>
    <div class="c-pt24 c-pb30 c-bg-white">
      <div class="c-flex-row c-aligni-center c-flexw-wrap c-ph24 priceBar">
        <div class="theme-fc c-fs40 c-fw600">
          <span class="c-fs26 c-lh">{{'￥' | iosPriceFilter}}</span><span class="c-lh">{{Number(couponInfo.productPrice).toFixed(2) | moneyStr}}</span>
        </div>
        <div v-if="couponInfo.crossedPrice && Number(couponInfo.crossedPrice) > 0" class="c-fs24 c-fc-gray c-ml16 c-text-decoration-through">
          <span class="c-fs20 c-lh">{{'￥' | iosPriceFilter}}</span><span class="c-lh">{{Number(couponInfo.crossedPrice).toFixed(2) | moneyStr)}}</span>
        </div>
      </div>
      <div class="c-fs30 c-ph24 c-fc-xblack c-lh44 c-fw600 c-text-ellipsis2 c-mt20">{{couponInfo.productName}}</div>
      <div class="c-flex-row c-justify-sb c-ph24 c-mt16">
        <div class="c-fs22 c-fc-gray c-pr24 c-text-ellipsis1">{{couponInfo.scope}}</div>
        <div v-if="couponInfo.showStock == 1" class="c-fs22 c-fc-gray c-flex-shrink0">库存：{{couponInfo.leftStockNum}}</div>
      </div>
    </div>
    <collocation-buy-com :prodInfo="{prodType: 5000, prodId: cId}" :relateCollocationArr="relateCollocation" :borderTop="true" class="c-mt4"></collocation-buy-com>
    <div class="c-mt16 c-ph24 c-pt28 c-pb24 c-bg-white">
      <div class="c-fs24 c-fc-xblack c-fw600 c-pb24">商品详情</div>
      <course-description ref="descriptions"></course-description>
    </div>
    <bottom-buy-com v-if="couponInfo"
      :ckFrom="5000"
      :isNeedPay="true"
      :showBuyButton="true"
    >
      <div v-if="couponInfo.putonStatus == 0 || couponInfo.leftStockNum <= 0 || couponInfo.isStopSale == 1" class="c-fs28 c-fc-white c-flex-row c-flex-center c-bg-ccc c-br36 c-flex-grow1 c-w0 c-hh64">
        {{couponInfo.putonStatus == 0 ? '已下架' : couponInfo.leftStockNum <= 0 ? '库存不足' : '已停售'}}
      </div>
      <div v-else-if="rcdId" @click="clickBuy" class="c-fs28 c-fc-white c-flex-row c-flex-center theme-bg c-br36 c-flex-grow1 c-w0 c-hh64">
        立即购买
      </div>
      <div v-else class="c-fs28 c-fc-white c-flex-row c-flex-center c-bg-ccc c-br36 c-flex-grow1 c-w0 c-hh64">
        商品已抢完，暂时缺货
      </div>
    </bottom-buy-com>
  </div>
</template>
<script>
import { utilJs } from "@/utils/common.js";
import courseDescription from '@/components/templates/courseDescription';
import BottomBuyCom from "@/components/templates/common/bottomBuyCom.vue";
import collocationBuyCom from '@/components/templates/collocationBuyCom';
import 'swiper/dist/css/swiper.css'
import { swiper, swiperSlide } from 'vue-awesome-swiper'
import { getBindPhoneSetting } from "@/utils/checkUnBindPhone.js";
import { COUPON_SCOPE_MAP } from "@/utils/constant.js";
let couponScopeMap = COUPON_SCOPE_MAP;
export default {
  name: 'ValuableCoupon',
  components: { swiper, swiperSlide, courseDescription, BottomBuyCom, collocationBuyCom },
  data() {
    return {
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : 'mb5_default',
      swiperList: [],
      swiperOption: {
      },
      swiperIndex: 0, //轮播图index
      cId: 0,
      couponInfo: "",
      bindPhoneSetting: null,
      rcdId: '',
      canNotBuy: false,
      relateCollocation: [],
    }
  },
  created() {
    utilJs.appShare(this);
    let that = this;
    this.swiperOption = {
      pagination: {
        el: '.swiper-pagination',
        bulletActiveClass: 'theme-bg',
        type: "custom"
      },
      loop: true,
      speed: 300,
      autoplay: {
        delay: 3000,
        disableOnInteraction: false,
      },
      autoHeight: true,
      updateOnImagesReady: true,
      observer: true,
      on: {
        slideChange: function () {
          that.swiperIndex = that.$refs.mySwiper.swiper.realIndex;
        }
      },
    };
  },
  methods: {
    getProdRelateCollocation() {
      utilJs.getMethod(`${global.apiurl}prodsCollocation/getProdRelateCollocation?prodType=5000&prodId=${this.cId}`,
        res => {
          this.relateCollocation = res.data ? res.data.slice(0, 3) : [];
        }
      );
    },
    clickBuy() {
      if (this.canNotBuy) {
        this.$showCjToast({
          text: "您的可购买次数已达到上限",
          type: "warn"
        });
        return;
      }
      if (this.bindPhoneSetting && this.bindPhoneSetting.buyBind && utilJs.goBindMobile()) {
        return;
      }
      let data = {cId: -1, extId: this.couponInfo.Id, ckFrom: global.ckFrom.valuableCoupon, isFromInvite: 0, goodsRoomId: this.$route.query.goodsRoomId || ''};
      if (this.$route.query.agentId) { // 因为优惠券支持多个服务商，所以要传具体从哪个服务商分享出来的
        data.agentId = this.$route.query.agentId;
      }
      this.$routerGo(this, "push", {
        path: '/homePage/course/coursePay',
        query: data
      });
    },
    getInfo() {
      utilJs.postMethod(`${global.apiurl}valuablecoupons/findValuableCoupon`, {id: Number(this.cId)},
        res => {
          if (res.retData && res.retData[0]) {
            if (res.retData[0].isDelete == 1) {
              this.$routerGo(this, "replace", { path: "/error/emptyPage", query: { info: '该券不存在' } });
              return
            }
            this.rcdId = res.rcdId;
            this.canNotBuy = res.isBuy && res.isBuy > 0 ? true : false;
            this.couponInfo = res.retData[0];
            try {
              this.swiperList = JSON.parse(this.couponInfo.productImage);
            } catch (err) {
              this.swiperList = [];
              console.log(err.message);
            }
            if (this.swiperList.length == 1) {
              this.swiperOption.autoplay = false;
              this.swiperOption.loop = false;
            }
            if (this.couponInfo.type == 1) {
              this.couponInfo.scope = this.couponInfo.name;
            } else if (this.couponInfo.type == 4) {
              this.couponInfo.scope = "适用于预约师资功能";
            } else {
              this.couponInfo.prodTypes = this.couponInfo.prodTypes ? this.couponInfo.prodTypes.split(",") : '';
              if (this.couponInfo.prodTypes && this.couponInfo.prodTypes.length > 0) {
                for (let i = 0; i < this.couponInfo.prodTypes.length; i++) {
                  this.couponInfo.prodTypes[i] = couponScopeMap[this.couponInfo.prodTypes[i]];
                }
              }
              this.couponInfo.scope = this.couponInfo.redeemType == 26 ? '全店商品可用' : (this.couponInfo.redeemType == 25 ? '适用于商城商品' : this.couponInfo.redeemType == 27 ? ('适用于' + (this.couponInfo.prodTypes ? this.couponInfo.prodTypes.join('、') : '')) : '指定商品可用')
            }
            try {
              this.couponInfo.productDesc = JSON.parse(this.couponInfo.productDesc);
              this.$refs.descriptions.getDescriptInfo(this.couponInfo.productDesc ? this.couponInfo.productDesc : []);
            } catch (err) {
              this.couponInfo.productDesc = [];
              this.$refs.descriptions.getDescriptInfo([]);
              console.log(err.message);
            }
            this.getProdRelateCollocation();
            this.wechatShare();
          } else {
            this.$routerGo(this, "replace", { path: "/error/emptyPage", query: { info: '暂无相关优惠券' } });
          }
        }
      );
    },
    //分享
    wechatShare: function () {
      let title = this.couponInfo.productName || window.localStorage.getItem("shareTitle");
      let shareImg = this.swiperList && this.swiperList.length > 0 ? this.swiperList[0] : window.localStorage.getItem("shareLogo");
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?id=${this.cId}&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = this.couponInfo.productIntroduction || window.localStorage.getItem("shareDesc") || "点击查看详情";
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () { });
    },
    //手机端分享
    appShare: function () {
      let title = this.couponInfo.productName || window.localStorage.getItem("shareTitle");
      let shareImg = this.swiperList && this.swiperList.length > 0 ? this.swiperList[0] : window.localStorage.getItem("shareLogo");
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?id=${this.cId}&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = window.localStorage.getItem("shareDesc") || "点击查看详情";
      utilJs.appShareTrue(title, shareImg, shareUrl, shareDesc);
    }
  },
  activated() {
    setDocumentTitle("优惠券");// eslint-disable-line
    this.swiperList = [];
    this.swiperIndex = 0; //轮播图index
    this.cId = this.$route.query.id || '';
    this.couponInfo = "";
    this.rcdId = '';
    this.canNotBuy = false;
    getBindPhoneSetting(92).then(res => {
      this.bindPhoneSetting = res;
    });
    this.getInfo();
    // this.wechatShare();
  },
  deactivated() { }
}
</script>
<style scoped>
.swiper-img-tag {
  width: 3.2rem;
  background-color: rgba(0, 0, 0, 0.25);
  border-radius: 0.1rem;
  height: 1.05rem;
}
.swiper-page-tag {
  width: 1.35rem;
  background:rgba(0,0,0,0.4);
  border-radius: 0.5rem;
  height: 0.7rem;
  color: #fff;
}
</style>


